<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Role;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AdminUserController extends Controller
{
    use AuthenticatesUsers;
    /**
     * Display a listing of the resource.
     *
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $where = [];
        if($request->start || $request->end || $request->keywords)
        {
            if($request->keywords) {
                $where[] = ['name', 'like', "%$request->keywords%"];
                }
            if($request->start && !$request->end)
            {
                $where[] = ['created_at','>=',$request->start.' 00:00:00'];
            }
            if($request->start && $request->end)
            {
                $where[] = ['created_at','>=',$request->start.' 00:00:00'];
                $where[] = ['created_at','<',$request->end.' 23:59:59'];
            }
        }
        if($where)
        {
            $page = AdminUser::where($where)
                ->with('getRole')
                ->paginate(10);
            $page->appends([
                'name'=>$request->keywords,
                'start'=>$request->start,
                'end'=>$request->end
            ]);
        }else {
            $page = AdminUser::with('getRole')->paginate(10);
        }
        $arr = ['start'=>$request->start,'end'=>$request->end,'keywords'=>$request->keywords];
        return view('Admin.AdminUser.index',compact('page','arr'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $role = Role::where('id','>',1)
            ->with('permissions')->get();
        return view('Admin.AdminUser.create',compact('role'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validate = Validator::make($request->all(),[
            'adminName'=>'required|min:4',
            'password'=>'required|min:5|confirmed',
            'password_confirmation'=>'required|min:5',
            'adminRole'=>'required',
            'sex'=>'required',
            'phone'=>'required',
            'email'=>'required|email',
            'department'=>'required'
        ]);
        if(!$validate->fails())
        {
            $exist = AdminUser::where(['username'=>$request->adminName])
                ->first();
            if(empty($exist)) {
                $res = AdminUser::create(['username' => $request->adminName, 'name'=>$request->adminName,'password' => Hash::make($request->password),'role'=>$request->adminRole,'sex'=>$request->sex,'mobile'=>$request->phone,'email'=>$request->email,'description'=>$request->description,'department'=>$request->department]);
                if ($res) {
                    $user = AdminUser::find($res->id);
                    $user -> assignRole($request->adminRole);
                    $this->set('data', ['id' => $res->id]);
                } else {
                    $this->set('code', 1);
                    $this->set('message', '服务器错误');
                }
            }else{
                $this->set('code', 2);
                $this->set('message', '用户已存在');
            }
        }
        else{
            $this->set('code',1);
            $this->set('message','输入错误');
        }
        return $this->ajaxResponse();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $show = AdminUser::where(['id'=>$id])
            ->first();
        $role = Role::with('permissions')->get();
        return view('Admin.AdminUser.edit',compact('show','role'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,$id)
    {
        $info = AdminUser::findOrFail($id);
        if($info){
                if($request->newpassword2 && $request->oldpassword == $request->newpassword2  ){
                    $password = Hash::make($request->newpassword2);
                }else{
                    $password = $info->password;
                }
                $username = $request->adminName ? $request->adminName : $info->username;
                $email = $request->email ? $request->email : $info->email;
                $sex = $request->sex ? $request->sex : $info->sex;
                $mobile = $request->phone ? $request->phone : $info->mobile;
                $role = $request->adminRole ? $request->adminRole : $info->role;
                $description = $request->description ? $request->description : $info->description;
                $department = $request->department ? $request->department : $info->department;
                $update = AdminUser::where(['id' => $id])
                    ->update(['username' => $username, 'password' => $password, 'email' => $email, 'sex' => $sex, 'mobile' => $mobile, 'role' => $role, 'description' => $description, 'department' => $department]);
                if (!$update) {
                    $this->set('code', 1);
                    $this->set('message', '修改失败');
                }
                if ($request->adminRole != $info->role) {
                    $user = AdminUser::find($id);
                    if (!$info->role) {
                        $user->assignRole($role);
                    } else {
                        $user->syncRoles($role);
                    }
                }

        }
        else{
            $this->set('code',1);
            $this->set('message','暂无该用户');
        }
        return $this->ajaxResponse();

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $exist = AdminUser::find($id);
        if($exist){
            $res = AdminUser::destroy($id);
            if(!$res){
                $this->set('code',1);
                $this->set('message','参数错误');
            }
        }else{
            $this->set('code',1);
            $this->set('message','参数错误');
        }
        return $this->ajaxResponse();
    }

    /**
     * @param Request $request
     * @return array
     * 管理员状态变更
     */
    public function setStatus(Request $request)
    {
        $validate = Validator::make($request->all(),[
            'uid'=>'required',
            'action'=>'required',
        ]);
        if(!$validate->fails())
        {
            $exist = AdminUser::where(['id'=>$request->uid])
                ->first();
            //启用
            if($request->action == 'on' && $exist->status == 0)
            {
                $update = AdminUser::where(['id'=>$request->uid])
                    ->update(['status'=>1]);
                if(!$update)
                {
                    $this->set('code',1);
                    $this->set('message','服务器错误');
                }
            }
            elseif($request->action == 'off' && $exist->status == 1)//禁用
            {
                $update = AdminUser::where(['id'=>$request->uid])
                    ->update(['status'=>0]);
                if(!$update)
                {
                    $this->set('code',1);
                    $this->set('message','服务器错误');
                }
            }else{
                $this->set('code',1);
                $this->set('message','操作错误');
            }
        }else{
            $this->set('code',1);
            $this->set('message','参数错误');
        }
        return $this->ajaxResponse();
    }
}
